package br.edu.unifei.cct720.alieninvasion.resources;

import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;

import javax.imageio.ImageIO;

import br.edu.unifei.cct720.alieninvasion.utils.Messages;

/**
 * Class to store the sprites used on the game
 * 
 * @author Felipe Knappe
 *
 */
public class SpriteStore {

	/** The single sprite instance */
	private static SpriteStore single = new SpriteStore();
	
	/**
	 * The collection to store all sprites in use
	 * @uml.property  name="sprites"
	 * @uml.associationEnd  qualifier="ref:java.lang.String br.edu.unifei.cct720.alieninvasion.resources.Sprite"
	 */
	private HashMap sprites = new HashMap();

	/**
	 * Method responsible for retrieve the instance of
	 * the SpriteStore
	 * 
	 * @return SpriteStore
	 */
	public static SpriteStore get() {
		single = (single != null) ? single : new SpriteStore();
		return single;
	}

	/**
	 * Method responsible for retrieve a specified
	 * sprite from the store
	 * 
	 * @param ref The sprite reference
	 * 
	 * @return Sprite
	 */
	public Sprite getSprite(String ref) {

		// Local variables declaration
		BufferedImage sourceImage = null;
		Sprite sprite = null;

		// In case sprite is already stored on "cache"
		if (sprites.get(ref) != null) {
			return (Sprite) sprites.get(ref);
		}

		
		//Otherwise, the sprite must be retrieve from the disk 
		try {
			URL url = this.getClass().getClassLoader().getResource(ref);
			sourceImage = ImageIO.read(url);
		} catch (IOException e) {
			Messages.showFailure(null, "Falha na leitura: " + ref);
		} 

		// Put the image available to the graphics buffer 
		GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
		Image image = gc.createCompatibleImage(sourceImage.getWidth(),sourceImage.getHeight(),Transparency.BITMASK);
		image.getGraphics().drawImage(sourceImage, 0, 0, null);

		// Instantiate the sprite with the retrieved image
		sprite = new Sprite(image);
		sprites.put(ref,sprite);

		return sprite;
	}
}
